package com.example.composableexample.requestpermission

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import androidx.activity.compose.ManagedActivityResultLauncher
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat
import com.google.accompanist.permissions.ExperimentalPermissionsApi
import com.google.accompanist.permissions.PermissionState
import com.google.accompanist.permissions.PermissionStatus
import com.google.accompanist.permissions.rememberMultiplePermissionsState
import com.google.accompanist.permissions.rememberPermissionState


/**
 * 通过Compose原生的方式
 */
@Preview
@Composable
fun RequestPermissionSimple() {

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(30.dp),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        val context = LocalContext.current
        val permission = Manifest.permission.CAMERA
        val launcher = rememberLauncherForActivityResult(
            contract = ActivityResultContracts.RequestPermission(),
            onResult = {
                if (it) {
                    // 打开相机
                } else {
                    // 显示对应的操作
                }
            }
        )
        Button(onClick = {
            checkAndRequestCameraPermission(
                context = context,
                permission = permission,
                launcher = launcher
            )
        }) {
            Text(text = "打开相机")
        }

        val permissions = arrayOf(
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION
        )
        val launcherMultiplePermissions = rememberLauncherForActivityResult(
            contract = ActivityResultContracts.RequestMultiplePermissions(),
            onResult = {
                val areGranted = it.values.reduce { acc, next -> acc && next }
                if (areGranted) {
                    // 得到Location
                } else {
                    // 没有得到
                }
            }
        )

        Button(onClick = {
            checkAndRequestLocationPermission(
                context = context,
                permissions = permissions,
                launcher = launcherMultiplePermissions
            )
        }) {
            Text(text = "获取位置权限")
        }

    }
}


@OptIn(ExperimentalPermissionsApi::class)
@Preview
@Composable
fun RequestPermissionSimple1() {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(30.dp),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        val cameraPermissionState = rememberPermissionState(permission = Manifest.permission.READ_EXTERNAL_STORAGE)
        val multiplePermissionsState = rememberMultiplePermissionsState(
            permissions = listOf(
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION
            )
        )

        when (cameraPermissionState.status) {
            PermissionStatus.Granted -> {
                Text("以获得相机权限")
            }
            is PermissionStatus.Denied -> {
                Column {
                    val textToShow =
                        if ((cameraPermissionState.status as PermissionStatus.Denied).shouldShowRationale) {
                            "未获得相机权限"
                        } else {
                            "请求权限"
                        }
                    Text(textToShow)
                    Button(onClick = { cameraPermissionState.launchPermissionRequest() }) {
                        Text("请求相机权限")
                    }
                }
            }
        }
        multiplePermissionsState.permissions.forEach {
            when (it.status) {
                is PermissionStatus.Granted -> {
                    Text(text = "获得位置权限")
                }
                is PermissionStatus.Denied -> {

                }
            }
        }
        Button(onClick = { multiplePermissionsState.launchMultiplePermissionRequest() }) {
            Text(text = "获取位置权限")
        }

    }

}

private fun checkAndRequestLocationPermission(
    context: Context,
    permissions: Array<String>,
    launcher: ManagedActivityResultLauncher<Array<String>, Map<String, Boolean>>
) {
    if (
        permissions.all {
            ContextCompat.checkSelfPermission(context, it) == PackageManager.PERMISSION_GRANTED
        }
    ) {
        // 得到权限
    } else {
        // 请求权限
        launcher.launch(permissions)
    }
}

private fun checkAndRequestCameraPermission(
    context: Context,
    permission: String,
    launcher: ManagedActivityResultLauncher<String, Boolean>
) {
    val permissionCheckResult = ContextCompat.checkSelfPermission(context, permission)
    if (permissionCheckResult == PackageManager.PERMISSION_GRANTED) {
        // 打开相机
    } else {
        // 请求权限
        launcher.launch(permission)
    }
}